package com.genesis.yunnanji.view.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.roundview.RoundTextView;
import com.genesis.yunnanji.Constants;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.adapter.BrandDetailsAdapter;
import com.genesis.yunnanji.adapter.OrderAdapter;
import com.genesis.yunnanji.bean.BaseBean;
import com.genesis.yunnanji.bean.BrandDetailsBeanList;
import com.genesis.yunnanji.bean.MessageBean;
import com.genesis.yunnanji.bean.MessageEventBean;
import com.genesis.yunnanji.bean.TrolleyListBean;
import com.genesis.yunnanji.utils.NetUtils;
import com.genesis.yunnanji.widget.RecycleViewDivider;
import com.genesis.yunnanji.widget.divider.SpacesItemDecoration;
import com.youth.xframe.utils.log.XLog;
import com.youth.xframe.widget.XToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.bining.footstone.utils.SharedUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 创建日期：2018/9/19 on 17:31
 * 作者:Kite
 * 描述:购物车
 */
public class ShoppingTrolleyFragment extends BaseFragment implements OrderAdapter.ModifyCountInterface {

    @BindView(R.id.actionbar_title)
    TextView actionbarTitle;

    @BindView(R.id.tv_right)
    TextView tvRight;

    @BindView(R.id.rv_order)
    RecyclerView rvOrder;

    @BindView(R.id.iv_choose)
    ImageView ivChoose;

    @BindView(R.id.tv_select_all)
    TextView tvSelectAll;

    @BindView(R.id.ll_total)
    LinearLayout llTotal;

    @BindView(R.id.tv_go_pay)
    TextView tvGoPay;

    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;

    @BindView(R.id.tv_clear)
    RoundTextView tvClear;


    private BrandDetailsAdapter mBrandDetailsAdapter;

    private List<BrandDetailsBeanList.ListBean> mBrandDetailsBeanList = new ArrayList<>();

    private OrderAdapter mOrderAdapter;

    private List<TrolleyListBean.ListBean> mOrderBeanList = new ArrayList<>();//购物车

    private boolean isEdit = true;//编辑按钮状态

    private boolean isSelectAll = false;//全选

    private int index = 0;

    private RecyclerView headerRcTrolley;

    private LinearLayout headerEmptyTrolley;

    private LinearLayout headerEnoLogin;

    private double totalPrice = 0.00;// 购买的商品总价

    private int totalCount = 0;// 购买的商品总数量

    /**
     * Fragment 实例
     */
    public static ShoppingTrolleyFragment newInstance(Object... pramars) {
        ShoppingTrolleyFragment fragment = new ShoppingTrolleyFragment();
        fragment.setArguments(getBundle(pramars));
        return fragment;
    }

    @Override
    public View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shopping_trolley, container, false);
        return view;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        actionbarTitle.setText("购物车");
        tvRight.setText("编辑");
        guessLike();
        initTrolley();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getTrolley(MessageEventBean messageEvent) {
        if (messageEvent.isDefault()) {
            initTrolley();
            //刷新购物车
        } else {
            XLog.e("======进faulse了======");
            headerEnoLogin.setVisibility(View.VISIBLE);
            headerEmptyTrolley.setVisibility(View.GONE);
            headerRcTrolley.setVisibility(View.GONE);
        }
    }

    private void getDate() {
        rvOrder.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mBrandDetailsAdapter = new BrandDetailsAdapter(getActivity(), rvOrder, mBrandDetailsBeanList);
        mBrandDetailsAdapter.notifyDataSetChanged();
        rvOrder.setAdapter(mBrandDetailsAdapter);
        rvOrder.setItemAnimator(new DefaultItemAnimator());
        rvOrder.addItemDecoration(new SpacesItemDecoration(0, 22, getResources().getColor(R.color.color_fff)));
//        rvOrder.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, 22, getResources().getColor(R.color.color_fff)));
//        rvOrder.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, 22, getResources().getColor(R.color.color_fff)));
        // 实例化头部
        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.header_shopping_trolley, rvOrder, false);
        headerRcTrolley = (RecyclerView) headerView.findViewById(R.id.rc_trolley);
        getHeadDate(headerRcTrolley);
        mBrandDetailsAdapter.addHeaderView(headerView);
        headerEmptyTrolley = (LinearLayout) headerView.findViewById(R.id.empty_trolley);
        headerEnoLogin = (LinearLayout) headerView.findViewById(R.id.no_login);
        if (mOrderBeanList.size() == 0) {
            headerEmptyTrolley.setVisibility(View.VISIBLE);
            headerRcTrolley.setVisibility(View.GONE);
        } else {
            headerEmptyTrolley.setVisibility(View.GONE);
            headerRcTrolley.setVisibility(View.VISIBLE);
        }
    }

    private void getHeadDate(RecyclerView recyclerView) {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mOrderAdapter = new OrderAdapter(getActivity(), mOrderBeanList);
        recyclerView.setAdapter(mOrderAdapter);
        mOrderAdapter.setModifyCountInterface(this);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        mOrderAdapter.setOnItemClickListener(new OrderAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(int pos, List<TrolleyListBean.ListBean> myLiveList) {
                TrolleyListBean.ListBean myLive = myLiveList.get(pos);
                boolean isSelect = myLive.isSelect();
                if (!isSelect) {
                    index++;
                    myLive.setSelect(true);
                    if (index == myLiveList.size()) {
                        isSelectAll = true;
                        tvSelectAll.setText("取消全选");
                    }
                    ivChoose.setBackgroundResource(R.drawable.icon_choose);
                    statistics();
                } else {
                    myLive.setSelect(false);
                    index--;
                    isSelectAll = false;
                    tvSelectAll.setText("全选");
                    statistics();
                }
                setBtnBackground(index);
                mOrderAdapter.notifyDataSetChanged();
            }
        });
        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, 12, getResources().getColor(R.color.color_eee)));
    }

    private void initTrolley() {
        JSONObject params = new JSONObject();
        try {
            params.put("p", 1);
            params.put("row", "20");
            params.put("__apptoken__", SharedUtils.getString(Constants.USER_TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.CART_INDEX)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<TrolleyListBean>, TrolleyListBean>(new SimpleCallBack<TrolleyListBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(TrolleyListBean bean) {
                        mOrderBeanList = bean.getList();
                        getDate();
                    }
                }) {
                });
    }

    private void guessLike() {
        JSONObject params = new JSONObject();
        try {
            params.put("row", "10");
            params.put("__apptoken__", SharedUtils.getString(Constants.USER_TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.INDEX_GUESSLIKE)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<BrandDetailsBeanList>, BrandDetailsBeanList>(new SimpleCallBack<BrandDetailsBeanList>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(BrandDetailsBeanList bean) {
                        mBrandDetailsBeanList = bean.getList();
                    }
                }) {
                });
    }

    @OnClick({R.id.tv_right, R.id.rl_choose, R.id.tv_total_price, R.id.tv_go_pay, R.id.tv_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                if (isEdit) {
                    tvRight.setText("完成");
                    isEdit = false;
                    llTotal.setVisibility(View.GONE);
                    tvGoPay.setVisibility(View.GONE);
                    tvClear.setVisibility(View.VISIBLE);
                    clearAll();
                } else {
                    tvRight.setText("编辑");
                    isEdit = true;
                    llTotal.setVisibility(View.VISIBLE);
                    tvGoPay.setVisibility(View.VISIBLE);
                    tvClear.setVisibility(View.GONE);
                    clearAll();
                }
                break;
            case R.id.rl_choose:
                selectAllMain();
                break;
            case R.id.tv_total_price:
                break;
            case R.id.tv_go_pay:
                settlementOrder(true);
                break;
            case R.id.tv_clear:
                settlementOrder(false);
                break;
        }
    }

    /**
     * 全选和反选
     */
    private void selectAllMain() {
        if (mOrderAdapter == null) return;
        if (!isSelectAll) {
            for (int i = 0, j = mOrderBeanList.size(); i < j; i++) {
                mOrderBeanList.get(i).setSelect(true);
            }
            index = mOrderBeanList.size();
            ivChoose.setBackgroundResource(R.drawable.icon_choose);
            tvSelectAll.setText("取消全选");
            isSelectAll = true;
            statistics();
        } else {
            for (int i = 0, j = mOrderBeanList.size(); i < j; i++) {
                mOrderBeanList.get(i).setSelect(false);
            }
            index = 0;
            tvSelectAll.setText("全选");
            ivChoose.setBackgroundResource(R.drawable.icon_unchoose);
            isSelectAll = false;
        }
        mOrderAdapter.notifyDataSetChanged();
        setBtnBackground(index);
    }

    private void clearAll() {
        for (int i = 0, j = mOrderBeanList.size(); i < j; i++) {
            mOrderBeanList.get(i).setSelect(false);
        }
        index = 0;
        tvSelectAll.setText("全选");
        ivChoose.setBackgroundResource(R.drawable.icon_unchoose);
        isSelectAll = false;
        mOrderAdapter.notifyDataSetChanged();
        setBtnBackground(0);
    }

    /**
     * 根据选择的数量是否为0来判断按钮的是否可点击.
     *
     * @param size
     */
    private void setBtnBackground(int size) {
        if (size != 0) {
            tvClear.setEnabled(true);
        } else {
            tvClear.setEnabled(false);
        }
    }

    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        TrolleyListBean.ListBean listBean = mOrderBeanList.get(position);
        int count = Integer.parseInt(listBean.getNums());
        count++;
        listBean.setNums(count + "");
        ((TextView) showCountView).setText(count + "");
        mOrderAdapter.notifyDataSetChanged();
        statistics();
    }

    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        TrolleyListBean.ListBean listBean = mOrderBeanList.get(position);
        int count = Integer.parseInt(listBean.getNums());
        if (count <= 1) {
            XToast.warning("至少选择一件商品");
            return;
        }
        count--;
        listBean.setNums(count + "");
        ((TextView) showCountView).setText(count + "");
        mOrderAdapter.notifyDataSetChanged();
        statistics();
    }

    @Override
    public void childDelete(int position) {

    }

    /**
     * 结算订单、支付
     */
    private void settlementOrder(boolean isPay) {
        for (TrolleyListBean.ListBean listBean :
                mOrderBeanList) {
            boolean select = listBean.isSelect();
            if (select) {
                String id = listBean.getId();
                String nums = listBean.getNums();
                if (isPay) {
                    XToast.info(id + "----------" + nums);
                } else {
                    deleteTrolley(id);
                }
            }
        }
    }

    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalCount = 0;
        totalPrice = 0.00;
        for (int i = 0; i < mOrderBeanList.size(); i++) {
            TrolleyListBean.ListBean shoppingCartBean = mOrderBeanList.get(i);
            if (shoppingCartBean.isSelect()) {
                totalCount++;
                totalPrice += Integer.parseInt(shoppingCartBean.getNums()) * Double.valueOf(shoppingCartBean.getSale_price());
            }
        }
        tvTotalPrice.setText(totalPrice + "");
//        tvSettlement.setText("结算(" + totalCount + ")");
    }

    private void deleteTrolley(String id) {
        JSONObject params = new JSONObject();
        try {
            params.put("cartid", id);
            params.put("__apptoken__", SharedUtils.getString(Constants.USER_TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.CART_REMOVECART)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<MessageBean>, MessageBean>(new SimpleCallBack<MessageBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(MessageBean bean) {
                        initTrolley();
                    }
                }) {
                });
    }

}
